﻿using UnityEngine;
using System.Collections;

public class CharacterMovement : MonoBehaviour {

    public float turnSmoothing = 15f;
    public float speedDampTime = 0.1f;
    public float speed;
    public float jumpSpeed;
    public float turnSpeed;
    public float runSpeed;

    public AnimationClip idle;
    public AnimationClip walk;
    public AnimationClip jump;
    public AnimationClip run;
    public AnimationClip shooting;

    private new Animation  animation;
    private Transform playerTransform;
    private CharacterController controller;
    private bool isRunning;
    private Vector3 moveDirection;
    private Vector3 impact;

    private float remainingHeight;
    
    // Use this for initialization
	void Start () 
    {
        playerTransform = transform;
        animation = GetComponent<Animation>();
        controller = GetComponent<CharacterController>();
        //animation["Shooting"].AddMixingTransform(playerTransform.Find("Bip02/Bip02 Pelvis/Bip02 Spine/Bip02 Spine1/Bip02 Neck/Bip02 L Clavicle"));
        animation["Shooting"].AddMixingTransform(playerTransform.Find("Bip02/Bip02 Pelvis/Bip02 Spine"));
        moveDirection = Vector3.zero;
        impact = Vector3.zero;
	}
	
	// Update is called once per frame
	void FixedUpdate () 
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        if (impact.magnitude > 0.2)
        {
            controller.Move(impact * Time.deltaTime);
        }
        impact = Vector3.Lerp(impact, Vector3.zero, 5 * Time.deltaTime);
        MovementManagement(h,v);
	}

    void MovementManagement(float horizontal, float vertical)
    {

        transform.Rotate(0,horizontal*turnSpeed*Time.deltaTime,0);
       
        
        
        if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.LeftShift))
        {
            isRunning = false;
            
        }
        else if (Input.GetKey(KeyCode.W))
        {
            isRunning = true;
        }


        if (isRunning)
        {
            moveDirection = playerTransform.TransformDirection(Vector3.forward) * runSpeed;
            animation.Play(run.name);
        }
        else
        {
            moveDirection = playerTransform.TransformDirection(Vector3.forward) * speed;
            animation.Play(walk.name);
        }
    }
    
    public void AddImpact(Vector3 dir, float force)
    {
        dir.Normalize();
        if (dir.y < 0)
        {
            dir.y = -dir.y;
        }// reflect down force on the ground
        impact += dir.normalized * force;
    }
}
